#include "CEUtilities.h"

#include "CEGUIRadioBox.h"
#include "CEGUIButtonBase.h"
#include "CEGUIRadioBoxGroup.h"


CEGUIRadioBoxGroup::CEGUIRadioBoxGroup(const string& groupname)
{
	m_sGroupName = groupname;
	m_pDefaultElement = NULL;
}

CEGUIRadioBoxGroup::~CEGUIRadioBoxGroup()
{
	//should I write this function?
}

bool CEGUIRadioBoxGroup::AddElement(CEGUIRadioBox *radiobox)
{
	if(radiobox != NULL)
	{
		m_pRadioBoxGroup.push_back(radiobox);

		if(	m_pRadioBoxGroup.size() == 1)
			SetElementToDefault(radiobox->GetID());
		return true;
	}
	else
		return false;	
}

int CEGUIRadioBoxGroup::RemoveElement(int elementid)
{
	vector<CEGUIRadioBox*>::iterator p;
	for(p = m_pRadioBoxGroup.begin(); p != m_pRadioBoxGroup.end(); ++p)
	{
		if((*p)->GetID() == elementid)
		{
			m_pRadioBoxGroup.erase(p);
			return m_pRadioBoxGroup.size();
		}
	}
	return m_pRadioBoxGroup.size();
}

CEGUIRadioBox* CEGUIRadioBoxGroup::GetElement(int elementid)
{
	int size = m_pRadioBoxGroup.size();
	for(int i = 0; i < size; i++)
	{
		if(m_pRadioBoxGroup[i]->GetID() == elementid)
			return m_pRadioBoxGroup[i];
	}

	return NULL;
}


const string& CEGUIRadioBoxGroup::GetSelectedItemName() const
{
	static const string EMPTY_STR = "";
	int size = m_pRadioBoxGroup.size();
	for(int i = 0; i < size; i++)
	{
		if(m_pRadioBoxGroup[i]->IsChecked())
		{
			return m_pRadioBoxGroup[i]->GetName();
		}
	}
	return EMPTY_STR;
}



int CEGUIRadioBoxGroup::DeleteElement(int elementid)
{
	vector<CEGUIRadioBox*>::iterator p;
	for(p = m_pRadioBoxGroup.begin(); p != m_pRadioBoxGroup.end(); ++p)
	{
		if((*p)->GetID() == elementid)
		{
			delete (*p);
			m_pRadioBoxGroup.erase(p);
			return m_pRadioBoxGroup.size();
		}
	}
	return m_pRadioBoxGroup.size();
}

const string& CEGUIRadioBoxGroup::GetGroupName() const
{
	return m_sGroupName;
}

bool CEGUIRadioBoxGroup::SetElementToDefault(int elementid)
{
	CEGUIRadioBox * temp = GetElement(elementid);
	
	if(temp != NULL)
	{
		m_pDefaultElement = temp;
		Update(elementid);
		return true;
	}
	return false;
}

HRESULT CEGUIRadioBoxGroup::Update(int checkedid)
{
	CEGUIRadioBox * temp = GetElement(checkedid);
	if (!temp)
		return S_FALSE;

	int size = m_pRadioBoxGroup.size();
	for(int i = 0; i < size; i++)
	{
		if(m_pRadioBoxGroup[i]->IsChecked())
		{
			m_pRadioBoxGroup[i]->SetButtonStatus(CEGUIButtonBase::BTS_NORMAL);
			m_pRadioBoxGroup[i]->SetCheck(false);
		}
	}

	temp->SetButtonStatus(CEGUIButtonBase::BTS_BUTTONDOWN);
	temp->SetCheck(true);

	return S_OK;
}